﻿using System;
using System.Collections.Generic;
using System.Text;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using app.Models;
using AmuTools;

namespace app.Api
{
    static class MesHelper
    {
        private static Phone mes_config = null;
        private static Dictionary<string, Template> mes_type_config = null;

        private static void InitConfig()
        {
            if(mes_config == null)
            {
                UpdateConfig();
            }
        }

        public static void UpdateConfig()
        {
            mes_config = G.DB.Get<Phone>(new Cd().And("selected = 1").Render()).GetFirstEntity();
            List<Template> template_list = G.DB.Get<Template>(new Cd().And("type_1 = 'message'").And("selected = 1").Render()).GetFirstTableList();
            Dictionary<string, Template> dic = new Dictionary<string, Template>();
            foreach (Template t in template_list)
            {
                dic.Add(t.type_2, t);
            }
            mes_type_config = dic;
        }

        /// <summary>
        /// 验证手机号
        /// </summary>
        /// <param name="txtPhoneNum"></param>
        /// <returns></returns>
        public static Boolean CheckPhoneNumber(string txtPhoneNum)
        {
            string regex = "^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$";
            //string regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
            return System.Text.RegularExpressions.Regex.IsMatch(txtPhoneNum, regex);
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public static string GetCode()
        {
            int number;
            char code;
            string checkCode = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 6; i++)
            {
                number = random.Next();
                code = (char)('0' + (char)(number % 10));
                checkCode += code.ToString();
            }
            return checkCode;
        }

        /// <summary>
        /// 手机注册时发的短信
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <param name="Code">验证码</param>
        /// <returns></returns>
        public static string SendRegisterMes(string phone_numbers, string code)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("code", code);
            return SendMessage(MesType.Register, phone_numbers, dic);
        }

        /// <summary>
        /// 发送系统消息
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string SendMes(string phone_numbers, string username)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("name", username);
            return SendMessage(MesType.HasMessage, phone_numbers, dic);
        }
        /// <summary>
        /// 发送解绑手机信息
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <param name="code"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string SendUnbindMes(string phone_numbers, string code, string username)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("name", username);
            dic.Add("code", code);
            return SendMessage(MesType.UnbindPhoneNumber, phone_numbers, dic);
        }
        /// <summary>
        /// 发送绑定手机信息
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <param name="code"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string SendBindMes(string phone_numbers, string code, string username)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("name", username);
            dic.Add("code", code);
            return SendMessage(MesType.BindPhoneNumber, phone_numbers, dic);
        }

        /// <summary>
        /// 发送重置密码短信
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <param name="code"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string SendRepassMes(string phone_numbers, string code, string username)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("name", username);
            dic.Add("code", code);
            return SendMessage(MesType.ResetPassword, phone_numbers, dic);
        }

        /// <summary>
        /// 需求方请求服务方，发送短信通知服务方
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <returns></returns>
        public static string SendDemandRequestServiceMes(string phone_numbers)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            return SendMessage(MesType.DemandRequestService, phone_numbers, dic);
        }

        /// <summary>
        /// 服务方请求需求方，发送短信通知需求方
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <returns></returns>
        public static string SendServiceRequestDemandMes(string phone_numbers)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            return SendMessage(MesType.ServiceRequestDemand, phone_numbers, dic);
        }

        /// <summary>
        /// 对接有新进展短信
        /// </summary>
        /// <param name="phone_numbers">手机号</param>
        /// <returns></returns>
        public static string SendAbutmentProgressMes(string phone_numbers)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            return SendMessage(MesType.NewAbutmentProgress, phone_numbers, dic);
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="number"></param>
        /// <param name="template"></param>
        /// <param name="signame"></param>
        /// <param name="code"></param>
        //public static string SendValidateCode(string accessKeyId,string accessKeySecret,string number,string template,string signame,string code)
        //{
        //    string flag = "";
        //    String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        //    String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //    //String accessKeyId = "LTAIQrIw19MEAl2l";//你的accessKeyId，参考本文档步骤2
        //    //String accessKeySecret = "wXEBAO8hzsN6YaQt6Mmk0ugoeNbahx";//你的accessKeySecret，参考本文档步骤2
        //    IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        //    //IAcsClient client = new DefaultAcsClient(profile);
        //    // SingleSendSmsRequest request = new SingleSendSmsRequest();
        //    //初始化ascClient,暂时不支持多region（请勿修改）
        //    DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        //    IAcsClient acsClient = new DefaultAcsClient(profile);
        //    SendSmsRequest request = new SendSmsRequest();
        //    try
        //    {
        //        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        //        request.PhoneNumbers = number;
        //        //必填:短信签名-可在短信控制台中找到
        //        request.SignName = signame;
        //        //必填:短信模板-可在短信控制台中找到
        //        request.TemplateCode = template;
        //        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //        request.TemplateParam = "{ \"code\":\""+code

        //            +"\"}";
        //        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //        request.OutId = "yourOutId";
        //        //请求失败这里会抛ClientException异常
        //        SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
        //        if (sendSmsResponse.Code == "OK")
        //        {
        //            flag = "success";
        //        }
        //        else
        //        {
        //            flag = sendSmsResponse.Message;
        //        }

        //        //System.Console.WriteLine(sendSmsResponse.Message);
        //    }
        //    catch (ServerException e)
        //    {
        //        flag = "failed";
        //        System.Console.WriteLine("服务器错误");
        //    }
        //    catch (ClientException e)
        //    {
        //        flag = "failed";
        //        System.Console.WriteLine("请求错误");
        //    }
        //    return flag;

        //}
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="mes_type"></param>
        /// <param name="numbers">电话号用‘，’隔开</param>
        /// <param name="param">模板中要替换的参数</param>
        /// <returns></returns>
        public static string SendMessage(MesType mes_type, string numbers, Dictionary<string,string> param = null)
        {
            InitConfig();

            string flag = "";
            String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            //String accessKeyId = "LTAIQrIw19MEAl2l";//你的accessKeyId，参考本文档步骤2
            //String accessKeySecret = "wXEBAO8hzsN6YaQt6Mmk0ugoeNbahx";//你的accessKeySecret，参考本文档步骤2
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", mes_config.accessKeyId, mes_config.accessKeySecret);
            //IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();
            //初始化ascClient,暂时不支持多region（请勿修改）
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = numbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = mes_config.sign;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = mes_type_config[((int)mes_type).ToString()].content;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                if (param != null)
                {
                    foreach (var it in param)
                    {
                        request.TemplateParam = "{ \"" + it.Key + "\":\"" + it.Value + "\"}";
                    }
                }
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "yourOutId";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                if (sendSmsResponse.Code == "OK")
                {
                    flag = "success";
                }
                else
                {
                    flag = sendSmsResponse.Message;
                }

                //System.Console.WriteLine(sendSmsResponse.Message);
            }
            catch (ServerException e)
            {
                flag = "failed";
                System.Console.WriteLine("服务器错误");
            }
            catch (ClientException e)
            {
                flag = "failed";
                System.Console.WriteLine("请求错误");
            }
            catch(Exception e)
            {
                flag = "failed";
            }
            return flag;

        }
    }

    enum MesType
    {
        Register = 1,
        ResetPassword = 2,
        BindPhoneNumber = 3,
        UnbindPhoneNumber = 4,
        HasMessage = 5,
        DemandRequestService = 6,
        ServiceRequestDemand = 7,
        NewAbutmentProgress = 8
    }
}